package com.example.back.Controller;

import com.example.back.Annotation.PassToken;
import com.example.back.Annotation.UserLoginToken;
import com.example.back.Entity.User;
import com.example.back.NonRepEntity.NickNameAndSoldNum;
import com.example.back.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 用户管理接口
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    private UserRepository userRepository;


    //根据ID查找用户
    @UserLoginToken
    @GetMapping("/{uid}")
    public User findUserByUserId(@PathVariable("uid") long uid) {
        return userRepository.findUserByUserId(uid);
    }

    //查找全部用户
    @UserLoginToken
    @GetMapping("/list")
    public List<User> findAllUser() {
        return userRepository.findAll();
    }

    //获取销量最高的5个用户
    @UserLoginToken
    @GetMapping("/topSeller")
    public List<NickNameAndSoldNum> findTopSeller() {
        Pageable pageable = PageRequest.of(0, 5, Sort.Direction.DESC, "soldNum");
        return userRepository.findTopSeller(pageable);
    }


    //这里查看用户名是否已存在
    @PassToken
    @GetMapping("/userName/{userName}")
    public boolean findUserByUserName(@PathVariable("userName") String userName) {
        return userRepository.findUserByUserName(userName) != null;
    }

    //发邮件找回密码
    @GetMapping("/findPassword/{userName}")
    public boolean findPassword(@PathVariable("userName") String userName) {
        try {
            User TUser = userRepository.findUserByUserName(userName);
            sendEmailForPassword(TUser.getEmail(), TUser.getUserPassword());
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private void sendEmailForPassword(String email, String password) {
        SimpleMailMessage smm = new SimpleMailMessage();
        String sendText = "这是你的密码：\n  " + password + "\n可别再搞丢了嗷！";
        smm.setSubject("密码找回"); // 设置邮件主题
        smm.setFrom("yang1819201341@foxmail.com"); // 设置邮箱发送者
        smm.setTo(email); // 设置邮件接收者，可以有多个接收者
        smm.setSentDate(new Date());    // 设置邮件发送日期
        smm.setText("这是测试邮件的正文");   // 设置邮件的正文
        javaMailSender.send(smm);
    }

    private void sendEmailForEmailChange(String newEmail) {
        SimpleMailMessage smm = new SimpleMailMessage();
        String sendText = "您已经将邮箱更改为此邮箱\n如果您未订阅此邮件，请忽略";
        smm.setSubject("邮箱更改"); // 设置邮件主题
        smm.setFrom("yang1819201341@foxmail.com"); // 设置邮箱发送者
        smm.setTo(newEmail); // 设置邮件接收者，可以有多个接收者
        smm.setSentDate(new Date());    // 设置邮件发送日期
        smm.setText(sendText);   // 设置邮件的正文
        javaMailSender.send(smm);
    }

    //输入密码错误给上锁
    @PostMapping("/limit/{userName}")
    public boolean limitUserByUserName(@PathVariable("userName") String userName) {
        try {
            User Tuser = userRepository.findUserByUserName(userName);
            Tuser.setLockedTimeStamp(new Date().getTime());
            userRepository.save(Tuser);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //更改用户信息
    @UserLoginToken
    @PatchMapping("/setting/{userId}/{changeItem}/{newValue}")
    public boolean changeUserItem(@PathVariable("changeItem") String changeItem,
                                  @PathVariable("newValue") String newValue,
                                  @PathVariable("userId") long userId) {
        try {
            User TUser = userRepository.findUserByUserId(userId);
            switch (changeItem) {
                case "userName": {
                    TUser.setNickName(newValue);
                }
                break;
                case "userBrief": {
                    TUser.setUserBrief(newValue);
                }
                break;
                case "email": {
                    TUser.setEmail(newValue);
//                    sendEmailForEmailChange(newValue);
                }
                break;
                case "location": {
                    TUser.setLocation(newValue);
                }
                break;
            }
            userRepository.save(TUser);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
